<?php

namespace frontend\components\sitemap;

use Yii;
use frontend\models\Config;
use frontend\models\Menu as Category;
use frontend\models\Page;
use frontend\models\product\bin\ProductBin;

class SitemapBuilder extends \thirdpart\module\googlesitemapgenerator\GoogleSitemapGeneratorStandardBuilder
{

    /**
     * Generates the content for the post sitemap
     *
     * @param $gsg GoogleSitemapGenerator
     * @param $params string
     */
    public function BuildPosts($gsg, $params, $settings = [])
    {
        if(!$pts = strrpos($params, "-")) return;

		$pts = strrpos($params, "-", $pts - strlen($params) - 1);

		$postType = substr($params, 0, $pts);

		$postType = str_replace('pt-', '', $postType);

		if(!$postType ) return;

		$params = substr($params, $pts + 1);

		$date = explode('-', $params);

		$start_at = $params . '-01 0:0:0';

		$date['1'] = (int)$date['1'] + 1;
		$date['0'] = $date['1'] > 12 ? ((int)$date['0'] + 1) : $date['0'];
		$date['1'] = $date['1'] > 12 ? 1 : $date['1'];
		$end_at = implode('-', $date);
		$end_at = $end_at . '-01 0:0:0';

        if( $postType == 'blogsingle' ){
            $query = Page::find()->where(['type'=>'blog', 'status'=>1])
                    ->andWhere('updated_at >= :key0 AND updated_at < :key1', [':key0'=>strtotime($start_at), ':key1'=>strtotime($end_at)])
                    ->orderBy("updated_at desc, sort_order asc");
            foreach($query->each() as $row){
                $url = Yii::$app->urlManager->createAbsoluteUrl(['/blog/detail',
                                        'id'=>$row['id']], true);
                $last = $row['updated_at'];
    
                $priority = isset($settings['blogsingle']) ? $settings['blogsingle'] : '0.5';
    
                $gsg->AddUrl($url, $last, 'monthly', $priority);
            }
	        
		}
        
    }



    /**
     * Generates the misc sitemap
     *
     * @param $gsg GoogleSitemapGenerator
     */
    public function BuildMisc($gsg, $settings = [])
    {
        $home = Yii::$app->urlManager->createAbsoluteUrl('/', true);
        $gsg->AddUrl($home, time(), 'daily', empty($settings['home']) ? 1 : $settings['home']);
        $has_url = [];
        $qsetting = 0.8;
        foreach($this->getData() as $key => $menu){
            $url = Config::setUrl($menu);

            if( $url === '/login.html') continue;
            if( $url === false ) continue;

            if( is_array($url)){
                $url = Yii::$app->urlManager->createAbsoluteUrl($url, true);
            }else{
                if( Yii::$app->language == 'zh-TW'){
                    $url = SITE_URL . '/zh' . $url;
                }elseif( Yii::$app->language == 'zh-CN'){
                    $url = SITE_URL . '/cn'. $url;
                }else{
                    $url = SITE_URL . $url;
                }
            }
            $last = time();
            if( !empty($menu['model']) ){
                $page = Page::findOne($menu['model']);
                $last = !empty($page) ? $page->updated_at : time();
            }

            if( in_array($url, $has_url)) continue;

            // $gsg->AddUrl($url, $last, 'monthly');
            $gsg->AddUrl($url, $last, 'daily', $qsetting);
            $has_url[] = $url;
        }
        $this->productMenu($gsg, $settings);
        $this->productCategoryMenu($gsg, $settings);
    }


    public function Index($gsg)
    {
        $this->BuildMisc($gsg, $gsg->configs);
        $newssingles = (new \yii\db\Query())->select([
            'FROM_UNIXTIME(p.updated_at,"%Y") as year',
            'FROM_UNIXTIME(p.updated_at,"%m") as month',
            'p.updated_at'
            ])
            ->from("{{%page}} p")
            ->where('p.status=1')
            ->andWhere(['p.type'=>'blog'])
            ->groupBy(['FROM_UNIXTIME(p.updated_at,"%Y")',
                        'FROM_UNIXTIME(p.updated_at,"%m")'])
            ->orderBy("p.updated_at desc, p.sort_order asc")
            ->all();
            

        foreach ((array)$newssingles as $newssingle) {
            $this->BuildPosts($gsg, 'pt-' . "blogsingle-" . sprintf("%04d-%02d", $newssingle['year'], $newssingle['month']), $gsg->configs);
        }
    }

    public function getData()
    {

        $query = Category::find()->cache(24 * 60 * 60)->with(['meta', 'icon'])
            ->where(['status' => Category::STATUS_ACTIVE]);
        $value = $query->orderBy('sort_order asc, id asc')->asArray()->all();
        return $value;
    }

    public function productMenu($gsg, $settings = []){
        $categorys = ProductBin::findLocations();
        $qsetting = 0.8;
        foreach ((array)$categorys as $child) {
            $url = Yii::$app->urlManager->createAbsoluteUrl(['/product/default/index',
                                        'country'=>$child['id']], true);
            $child_categorys = ProductBin::findLocations($child['id']);
            $last = time();
            $gsg->AddUrl($url, $last, 'daily', $qsetting);
            foreach ((array)$child_categorys as $child_v) {
                $url = Yii::$app->urlManager->createAbsoluteUrl(['/product/default/index',
                                        'area'=>$child_v['id']], true);
                $gsg->AddUrl($url, $last, 'daily', $qsetting);                                        
            }
        }
        /*葡萄品種*/
        $categorys = ProductBin::findCategorys(0, 'grape');
        foreach ((array)$categorys as $child) {
            $url = Yii::$app->urlManager->createAbsoluteUrl(['/product/default/index',
                                        'grape'=>$child['id']], true);
            $gsg->AddUrl($url, $last, 'daily', $qsetting);
        }
        $url = Yii::$app->urlManager->createAbsoluteUrl(['/product/default/index',
                                        'type'=>'accessory'], true);
        $gsg->AddUrl($url, $last, 'daily', $qsetting);
    }
    public function productCategoryMenu($gsg, $settings = []){
        $categorys = ProductBin::findCategorys(0, 'product', function($query){
            return $query->andWhere('find_in_set("bq", tag_key)');
        });      
        $qsetting = 0.8;
        $last = time();
        foreach ((array)$categorys as $child) {
            if($child['id'] == 6){
                $url = Yii::$app->urlManager->createAbsoluteUrl(['/product/category/list'], true);
                $gsg->AddUrl($url, $last, 'daily', $qsetting);
            }else{
                $url = Yii::$app->urlManager->createAbsoluteUrl(['/product/category/list', 'category'=>$child['id']], true);
                $gsg->AddUrl($url, $last, 'daily', $qsetting);
            }
           
            $child_categorys = ProductBin::findCategorys($child['id']);
            
            if(!empty($child_categorys)){
                foreach ((array)$child_categorys as $child_v) {
                    $url = Yii::$app->urlManager->createAbsoluteUrl(['/product/category/list', 'category'=>$child_v['id']], true);
                    $gsg->AddUrl($url, $last, 'daily', $qsetting);
                }
                
            }
        }
    }
}
